package com.shizhanzhe.zxbapp.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.APP2;
import com.shizhanzhe.zxbapp.bean.App;
import com.shizhanzhe.zxbapp.bean.AppLoading;
import com.shizhanzhe.zxbapp.bean.CustomObject;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.home.AppDetailActivity;
import com.shizhanzhe.zxbapp.home.GVAdapter;
import com.shizhanzhe.zxbapp.home.HomeFragment;
import com.shizhanzhe.zxbapp.home.TaskDetailActivity;
import com.shizhanzhe.zxbapp.ui.LoginActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.vip.GameActivity;
import com.shizhanzhe.zxbapp.vip.VIPActivity;
import com.shizhanzhe.zxbapp.widget.ErrorCallback;
import com.shizhanzhe.zxbapp.widget.SignDialog;

import java.util.ArrayList;
import java.util.List;

import xcs.ert.jlj.os.PointsChangeNotify;
import xcs.ert.jlj.os.df.AdExtraTaskStatus;
import xcs.ert.jlj.os.df.AppExtraTaskObject;
import xcs.ert.jlj.os.df.AppExtraTaskObjectList;
import xcs.ert.jlj.os.df.AppSummaryDataInterface;
import xcs.ert.jlj.os.df.AppSummaryObject;
import xcs.ert.jlj.os.df.AppSummaryObjectList;
import xcs.ert.jlj.os.df.DiyOfferWallManager;

/**
 * 应用
 * Created by zz9527 on 2018/10/15.
 */
public class TabTaskFragment extends Fragment implements PointsChangeNotify {
    private GVAdapter gvAdapter;
    private ListView gv;
    private ListView zj;
    private LoadingAdapter zjAdapter;
    private SmartRefreshLayout refresh;
    private ArrayList<CustomObject> zxcustomObjectArrayList;
    private ArrayList<CustomObject> zjcustomObjectArrayList;
    private View nodata;
    LoadService loadService;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        //第一步：获取布局View
        View rootView = View.inflate(getActivity(), R.layout.fragment_tab_task, null);
        //第二步：注册布局View
        loadService = LoadSir.getDefault().register(rootView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                // 重新加载逻辑
                getApp();
            }
        });
        //第三步：返回LoadSir生成的LoadLayout
        return loadService.getLoadLayout();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        getApp();
    }

    private void initView(View view) {
        final ImageView iv_zhengzaicanyu = view.findViewById(R.id.iv_zhengzaicanyu);
        final ImageView iv_kecanyu = view.findViewById(R.id.iv_kecanyu);
        final TextView tv_zhengzaicanyu = view.findViewById(R.id.tv_zhengzaicanyu);
        final TextView tv_kecanyu = view.findViewById(R.id.tv_kecanyu);
        nodata = view.findViewById(R.id.nodata);
        view.findViewById(R.id.rl_fragment_ge_task_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                iv_kecanyu.setImageResource(R.mipmap.kcy_s);
                iv_zhengzaicanyu.setImageResource(R.mipmap.jxz);
                tv_zhengzaicanyu.setTextColor(getResources().getColor(R.color.tv_selector2));
                tv_kecanyu.setTextColor(getResources().getColor(R.color.tv_selector));
                gv.setVisibility(View.VISIBLE);
                zj.setVisibility(View.GONE);
                getApp();
            }
        });
        view.findViewById(R.id.rl_zhengzaicanyuarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_kecanyu.setImageResource(R.mipmap.kcy);
                iv_zhengzaicanyu.setImageResource(R.mipmap.jxz_s);
                tv_zhengzaicanyu.setTextColor(getResources().getColor(R.color.tv_selector));
                tv_kecanyu.setTextColor(getResources().getColor(R.color.tv_selector2));
                getAppLoading();
            }
        });
        view.findViewById(R.id.ll_kecanyu).setSelected(true);
        gv = view.findViewById(R.id.task_zuixin);
        zj = view.findViewById(R.id.task_zhuijia);
        refresh = view.findViewById(R.id.refresh);
        //设置 Header 样式
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                iv_kecanyu.setImageResource(R.mipmap.kcy_s);
                iv_zhengzaicanyu.setImageResource(R.mipmap.jxz);
                tv_zhengzaicanyu.setTextColor(getResources().getColor(R.color.tv_selector2));
                tv_kecanyu.setTextColor(getResources().getColor(R.color.tv_selector));
                getApp();
            }
        });
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                if (zxcustomObjectArrayList.get(i).getAppSummaryObject().getAppName().contains("#")) {
                    intent.setClass(getActivity(), AppDetailActivity.class);
                    intent.putExtra("app", zxcustomObjectArrayList.get(i).getAppSummaryObject().getAppName());
                } else {
                    intent.setClass(getActivity(), TaskDetailActivity.class);
                    intent.putExtra("ad", zxcustomObjectArrayList.get(i).getAppSummaryObject());
                }
                startActivity(intent);
            }
        });
        zj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                if (zjcustomObjectArrayList.get(i).getAppSummaryObject().getAppName().contains("#")) {
                    intent.setClass(getActivity(), AppDetailActivity.class);
                    intent.putExtra("app", zjcustomObjectArrayList.get(i).getAppSummaryObject().getAppName());
                } else {
                    intent.setClass(getActivity(), TaskDetailActivity.class);
                    intent.putExtra("ad", zjcustomObjectArrayList.get(i).getAppSummaryObject());
                }
                startActivity(intent);
            }
        });
        view.findViewById(R.id.banner_task).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (onButtonClick != null) {
//                    onButtonClick.onClick(banner);
//                }
                startActivity(new Intent(getContext(), GameActivity.class));
            }
        });
    }

    private OnButtonClick onButtonClick;//2、定义接口成员变量

    //定义接口变量的get方法
    public OnButtonClick getOnButtonClick() {
        return onButtonClick;
    }

    //定义接口变量的set方法
    public void setOnButtonClick(OnButtonClick onButtonClick) {
        this.onButtonClick = onButtonClick;
    }

    //1、定义接口
    public interface OnButtonClick {
        public void onClick(View view);
    }

    private void getApp() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.APP(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    zxcustomObjectArrayList = new ArrayList<CustomObject>();
                    List<App.DataBean> data = gson.fromJson(json, App.class).getData();
                    for (int k = 0; k < data.size(); ++k) {
                        if (data.get(k).getProtype() == 0) {
                            CustomObject customObject = new CustomObject();
                            APP2 appSummaryObject = new APP2();
                            if (data.get(k).getProtasktype() == 0) {
                                appSummaryObject.setAppName(data.get(k).getProname() + "#" + data.get(k).getProid() + "#" + data.get(k).getBaoname() + "#" + data.get(k).getDaninstall());
                            } else {
                                appSummaryObject.setAppName(data.get(k).getProname() + "#" + data.get(k).getProid() + "#" + data.get(k).getBaoname() + "#" + data.get(k).getTotalamount());
                            }
                            appSummaryObject.setPoints((int) (Double.parseDouble(data.get(k).getDaninstall())));
                            customObject.setAppSummaryObject(appSummaryObject);
                            customObject.setAppicon(data.get(k).getAppicon());
                            zxcustomObjectArrayList.add(customObject);
                        }
                    }
                    getData();
                } else {
                    loadService.showCallback(ErrorCallback.class);
                }
            }
        });
    }

    private void getAppLoading() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.APPLOAD(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Gson gson = new Gson();
                        zjcustomObjectArrayList = new ArrayList<CustomObject>();
                        List<AppLoading.DataBean> data = gson.fromJson(json, AppLoading.class).getData();
                        for (int k = 0; k < data.size(); ++k) {
                            if (data.get(k).getInstatus() == 1) {
                                continue;
                            }
                            CustomObject customObject = new CustomObject();
                            APP2 appSummaryObject = new APP2();
                            appSummaryObject.setAppName(data.get(k).getProname() + "#" + data.get(k).getProid() + "#" + data.get(k).getBaoname() + "#" + data.get(k).getPrice());
                            appSummaryObject.setPoints((int) (Double.parseDouble(data.get(k).getPrice())));
                            appSummaryObject.setDetail(data.get(k).getDname());
                            appSummaryObject.setStatus(data.get(k).getInstatus());
                            customObject.setAppSummaryObject(appSummaryObject);
                            customObject.setAppicon(data.get(k).getAppicon());
                            customObject.setShowMultSameAd(false);
                            zjcustomObjectArrayList.add(customObject);
                        }
                        getData2();
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    private void getData() {
        // 获取指定类型 的广告，并更新listview，下面展示两种加载方式，开发者可选择适合自己的方式
        // 异步加载方式
        // 请求类型，页码，请求数量，回调接口
        DiyOfferWallManager.getInstance(getContext())
                .loadOfferWallAdList(1, 1, 20, new AppSummaryDataInterface() {

                    /**
                     * 当成功获取到积分墙列表数据的时候，会回调这个方法（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     * 注意：列表数据有可能为空（比如：没有广告的时候），开发者处理之前，请先判断列表是否为空，大小是否大与0
                     */
                    @Override
                    public void onLoadAppSumDataSuccess(Context context, final AppSummaryObjectList adList) {
                        if (adList == null || adList.isEmpty()) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                        mSwipeRefreshLayout.setRefreshing(false);
//                                        mSwipeRefreshLayout.setPushRefreshFinish();

                                }
                            });
                        } else {

                            for (int k = 0; k < adList.size(); k++) {
                                CustomObject customObject = new CustomObject();
                                customObject.setAppSummaryObject(adList.get(k));
                                if (adList.get(k).getIconUrl() == null) {
                                    customObject.setAppicon("");
                                } else {
                                    customObject.setAppicon(adList.get(k).getIconUrl());
                                }
                                zxcustomObjectArrayList.add(customObject);
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (zxcustomObjectArrayList.size() == 0) {
                                        nodata.setVisibility(View.VISIBLE);
                                        gv.setVisibility(View.GONE);
                                        zj.setVisibility(View.GONE);
                                    } else {
                                        nodata.setVisibility(View.GONE);
                                        gv.setVisibility(View.VISIBLE);
                                        zj.setVisibility(View.GONE);
                                    }
                                    gvAdapter = new GVAdapter(zxcustomObjectArrayList, getContext(), 2);
                                    gv.setAdapter(gvAdapter);
                                    gv.setFocusable(false);
                                    loadService.showSuccess();
//                                        Toast.makeText(getContext(),
//                                                String.format("请求成功\n请求页码：%s\n请求数量：%s\n实际返回数量:%s\n当天新任务限制:%s\n已安装的新任务数:%s", adList.getPageIndex(),
//                                                        adList.getPerPageNumber(), adList.size(), adList.getInstallLimit(), adList.getInstallTimes
//                                                                ()),
//                                                Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        if (adList != null) {
                            updateLimitInfo(adList.getInstallLimit(), adList.getInstallTimes());
                        }

                    }

                    /**
                     * 因为网络问题而导致请求失败时，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailed() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(getContext(), "请求失败，请检查网络～", Toast.LENGTH_LONG).show();
                                gv.setVisibility(View.VISIBLE);
                                zj.setVisibility(View.GONE);
                                gvAdapter = new GVAdapter(zxcustomObjectArrayList, getContext(), 2);
                                gv.setAdapter(gvAdapter);
                            }
                        });
                    }

                    /**
                     * 请求成功，但是返回有米错误代码时候，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailedWithErrorCode(final int code) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(getContext(), String.format("请求错误，错误代码 ： %d， 请联系客服", code),
//                                        Toast.LENGTH_LONG).show();
                                gv.setVisibility(View.VISIBLE);
                                zj.setVisibility(View.GONE);
                                gvAdapter = new GVAdapter(zxcustomObjectArrayList, getContext(), 2);
                                gv.setAdapter(gvAdapter);
                            }
                        });
                    }
                });
    }


    private void getData2() {
        // 获取指定类型 的广告，并更新listview，下面展示两种加载方式，开发者可选择适合自己的方式
        // 异步加载方式
        // 请求类型，页码，请求数量，回调接口
        DiyOfferWallManager.getInstance(getContext())
                .loadOfferWallAdList(6, 1, 30, new AppSummaryDataInterface() {

                    /**
                     * 当成功获取到积分墙列表数据的时候，会回调这个方法（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     * 注意：列表数据有可能为空（比如：没有广告的时候），开发者处理之前，请先判断列表是否为空，大小是否大与0
                     */
                    @Override
                    public void onLoadAppSumDataSuccess(Context context, final AppSummaryObjectList adList) {

                        for (int k = 0; k < adList.size(); ++k) {
                            AppSummaryObject appSummaryObject = adList.get(k);
                            AppExtraTaskObjectList extraTaskObjectList = appSummaryObject.getExtraTaskList();
                            for (int j = 0; j < extraTaskObjectList.size(); ++j) {
                                AppExtraTaskObject extraTaskObject = extraTaskObjectList.get(j);
                                if (extraTaskObject.getStatus() == AdExtraTaskStatus.IN_PROGRESS) {
                                    CustomObject customObject = new CustomObject();
                                    customObject.setAppSummaryObject(adList.get(k));
                                    customObject.setAppicon(adList.get(k).getIconUrl());
                                    customObject.setShowMultSameAd(true);
                                    customObject.setShowExtraTaskIndex(j);
                                    zjcustomObjectArrayList.add(customObject);
                                }
                                if (extraTaskObject.getStatus() == AdExtraTaskStatus.NOT_START) {
                                    CustomObject customObject = new CustomObject();
                                    customObject.setAppSummaryObject(adList.get(k));
                                    customObject.setAppicon(adList.get(k).getIconUrl());
                                    customObject.setShowMultSameAd(true);
                                    customObject.setShowExtraTaskIndex(j);
                                    zjcustomObjectArrayList.add(customObject);
                                    break;
                                }


                            }
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (zjcustomObjectArrayList.size() == 0) {
                                    nodata.setVisibility(View.VISIBLE);
                                    gv.setVisibility(View.GONE);
                                    zj.setVisibility(View.GONE);
                                } else {
                                    nodata.setVisibility(View.GONE);
                                    gv.setVisibility(View.GONE);
                                    zj.setVisibility(View.VISIBLE);
                                }
                                zjAdapter = new LoadingAdapter(zjcustomObjectArrayList, getContext());
                                zj.setAdapter(zjAdapter);
                                zj.setFocusable(false);

//                                        Toast.makeText(getContext(),
//                                                String.format("请求成功\n请求页码：%s\n请求数量：%s\n实际返回数量:%s\n当天新任务限制:%s\n已安装的新任务数:%s", adList.getPageIndex(),
//                                                        adList.getPerPageNumber(), adList.size(), adList.getInstallLimit(), adList.getInstallTimes
//                                                                ()),
//                                                Toast.LENGTH_LONG).show();
                            }
                        });

                        if (adList != null) {
                            updateLimitInfo(adList.getInstallLimit(), adList.getInstallTimes());
                        }

                    }

                    /**
                     * 因为网络问题而导致请求失败时，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailed() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(getContext(), "请求失败，请检查网络～", Toast.LENGTH_LONG).show();
                                gv.setVisibility(View.GONE);
                                zj.setVisibility(View.VISIBLE);
                                zjAdapter = new LoadingAdapter(zjcustomObjectArrayList, getContext());
                                zj.setAdapter(zjAdapter);
                            }
                        });
                    }

                    /**
                     * 请求成功，但是返回有米错误代码时候，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailedWithErrorCode(final int code) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(getContext(), String.format("请求错误，错误代码 ： %d， 请联系客服", code),
//                                        Toast.LENGTH_LONG).show();
                                gv.setVisibility(View.GONE);
                                zj.setVisibility(View.VISIBLE);
                                zjAdapter = new LoadingAdapter(zjcustomObjectArrayList, getContext());
                                zj.setAdapter(zjAdapter);
                            }
                        });
                    }
                });
    }

    /**
     * 更新用户当前可做的任务数
     * <p/>
     * 计算当前还可以做多少个处于《未完成状态》广告：安装上限-今天已经安装过的数量
     *
     * @param installLimit 当天新任务安装限制
     * @param installTimes 当天已经完成的新任务数量
     */
    private void updateLimitInfo(final int installLimit, final int installTimes) {
//        getActivity().runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                StringBuilder sb = new StringBuilder();
//                sb.append("可做任务数：");
//                sb.append(installLimit - installTimes);
//                updateLimitInfo(sb.toString());
//            }
//        });
    }

    @Override
    public void onPointBalanceChange(float v) {

    }
}
